﻿using System;
using Autofac;
using Hangfire;
using Identification.Importer.Core;
using Microsoft.Extensions.Logging;
using Serilog;
using Topshelf;
using Topshelf.Autofac;

namespace Identification.Importer.Job
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                // init serilog
                Log.Logger = new LoggerConfiguration()
                    .WriteTo.ColoredConsole()
                    .ReadFrom.AppSettings()
                    .CreateLogger();

                // register component into autofac container
                var builder = new ContainerBuilder();
                builder.RegisterModule(new ServiceDependencyModule());
                builder.RegisterModule(new JobDependencyModule());
                var container = builder.Build();

                // config hangfire ioc container
                GlobalConfiguration.Configuration.UseAutofacActivator(container);

                x.UseSerilog();
                x.UseAutofacContainer(container);

                x.RunAsLocalSystem();
                x.StartAutomaticallyDelayed();

                x.Service<ServiceComponent>(s =>
                {
                    // Let Topshelf use it
                    s.ConstructUsingAutofacContainer();
                    s.WhenStarted((service, control) =>
                    {
                        Log.Debug("Job has started");
                        return service.Start(control);
                    });

                    s.WhenStopped((service, control) =>
                    {
                        Log.Debug("Job has stopped");
                        return service.Stop(control);
                    });
                });

                x.SetStartTimeout(TimeSpan.FromSeconds(30));
                x.SetStopTimeout(TimeSpan.FromSeconds(30));

                x.OnException((exception) => { Log.Error("Exception thrown - " + exception.Message); });
            });
        }
    }
}